package com.why.whyojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.why.whyojcodesandbox.model.dto.ExecuteCodeRequest;
import com.why.whyojcodesandbox.model.dto.ExecuteCodeResponse;
import com.why.whyojcodesandbox.model.dto.ExecuteMessage;
import com.why.whyojcodesandbox.model.dto.JudgeInfo;
import com.why.whyojcodesandbox.model.enums.QuestionSubmitStatusEnum;
import com.why.whyojcodesandbox.utils.ProcessUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


public abstract class JavaNativeCodeSandBoxTemplate implements CodeSandBox{
    public static final String GLOBAL_CODE_DIR_NAME = "tempcode";
    public static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";



    /**
     * 接收执行请求，返回执行结果
     * @param executeCodeRequest
     * @return
     */
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setStatus(QuestionSubmitStatusEnum.FAILED.getValue());
        //1.获取输入用例和用户代码
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        //2.创建文件
        File userCodeFile = saveCodeToFile(code);
        //3.编译代码
        try {
            ExecuteMessage compileMessage = compileFile(userCodeFile);
            if (compileMessage.getErrorMessage() != null) {
                return executeCodeResponse;
            }
        } catch (Exception e) {
            return executeCodeResponse;
        }
        //4.执行代码
        List<ExecuteMessage> executeMessageList = runFile(userCodeFile, inputList);
        //5.处理返回结果
        messageToResponse(executeCodeResponse, executeMessageList, inputList);
        //6.删除文件
        deleteFile(userCodeFile);
        return executeCodeResponse;
    }

    /**
     * 将代码保存为文件
     * @param code
     * @return
     */
    public File saveCodeToFile(String code) {
        String userDir = System.getProperty("user.dir");
        System.out.println(userDir);
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }
        String parentCodePath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath =  parentCodePath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        return FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
    }

    /**
     * 编译文件
     * @param userCodeFile
     * @return
     */
    public ExecuteMessage compileFile(File userCodeFile) {
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            if (executeMessage.getExitValue() != 0) {
                throw new RuntimeException("编译错误");
            }
            return executeMessage;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 执行文件
     * @param userCodeFile
     * @param inputList
     * @return
     */
    public  List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList) {
        String parentCodePath = userCodeFile.getParentFile().getAbsolutePath();
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            String runCmd = String.format("java -Dfile.encoding=UTF-8 -cp %s Main %s", parentCodePath, inputArgs);
            try {
                Process runProcess = Runtime.getRuntime().exec(runCmd);
                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "运行");
                executeMessageList.add(executeMessage);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return executeMessageList;
    }

    /**
     * 处理输出的结果，生成response
     * @param executeCodeResponse
     * @param executeMessageList
     * @param inputList
     */
    public void messageToResponse(ExecuteCodeResponse executeCodeResponse, List<ExecuteMessage> executeMessageList, 
                                  List<String> inputList) {
        List<String> outputList = new ArrayList<>();
        Long maxTime = 0L;
        for (ExecuteMessage executeMessage : executeMessageList) {
            if (StrUtil.isNotBlank(executeMessage.getErrorMessage())) {
                executeCodeResponse.setMessage(executeMessage.getErrorMessage());
                break;
            }
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
            outputList.add(executeMessage.getMessage());
        }
        if (outputList.size() == inputList.size()) {
            executeCodeResponse.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());

        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        executeCodeResponse.setJudgeInfo(judgeInfo);
    }

    /**
     * 删除文件
     * @param userCodeFile
     * @return
     */
    public boolean deleteFile(File userCodeFile) {
        boolean del = true;
        if (userCodeFile.getParentFile() != null) {
            del = FileUtil.del(userCodeFile.getParentFile().getAbsolutePath());
            System.out.println("删除" + (del ? "成功" : "失败"));
        }
        return del;
    }

    /**
     * 生成错误响应
     * @param e
     * @return
     */
    public ExecuteCodeResponse getErrorResponse(Throwable e) {
    ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
    executeCodeResponse.setOutputList(new ArrayList<>());
    executeCodeResponse.setMessage(e.getMessage());
    executeCodeResponse.setStatus(2);
    executeCodeResponse.setJudgeInfo(new JudgeInfo());
    return executeCodeResponse;
}

}


